<template>
  <BasicLayout>
    <template #wrapper>
      <el-card style="padding: 0px 36px 0px 36px">
        <div style="display: flex;justify-content:space-between">
          <div>
            <router-link :to="{name:subjectType, params: {id: routerData.id, jump_id: 'subject'}}">
              <i class="el-icon-arrow-left" />
              <span>返回</span>
            </router-link>
          </div>
          <div>
            <el-button type="primary" size="mini" @click="addSubject()">编辑题目</el-button>
          </div>
        </div>
        <div v-if="subjectList.length>0">
          <div v-for="(value, index) in subjectList" :key="index">
            <!-- 题目 -->
            <p style="font-weight: bold;">{{ `${index+1}、${topicType[value.subject_type]}` }}</p>
            <el-row :gutter="10" style="line-height: 10px">
              <el-col :span="1.5">
<!--                <img v-if="urlTest.test(value.content)" :src="value.content" class="avatar">-->
<!--                <p v-else v-html="value.content" />-->
                    <p v-html="value.content" style="line-height: 2rem" />
              </el-col>
            </el-row>
            <!-- 答案 -->
            <ul style="list-style-type:none; padding-inline-start: initial">
              <li v-for="(val, idx) in value.answer" :key="idx" style="margin-bottom: 10px">
                <div v-if="urlTest.test(val[mapAnswer(idx)])" style="display: flex;width: 40%">
                  {{ `${mapAnswer(idx)}：` }}
                  <img
                    style="height: 100px;"
                    :src="val[mapAnswer(idx)]"
                    class="avatar"
                  >
                </div>
                <span v-else style="display: flex;align-items: center;">
                  <span>{{ `${mapAnswer(idx)}：` }}</span>
                  <span v-html="val[mapAnswer(idx)]" />
                </span>
              </li>
            </ul>
            <p>题目解析：</p>
            <el-row :gutter="10" style="line-height: 10px">
              <el-col :span="1.5">
                <img v-if="urlTest.test(value.analysis)" :src="value.analysis" class="avatar">
                <p v-else style="line-height: 24px">{{ value.analysis }}</p>
              </el-col>
            </el-row>
          </div>
        </div>
        <el-empty v-else :image-size="150" />
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>
      <Exercises :visible="visible" :id-list="idList" @cancel="cancel" @submitForm="submitForm" />
      <!-- <el-dialog title="添加题目" :visible.sync="visible" destroy-on-close @closed="onClosed">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="题目类型" prop="exercise_type">
            <el-select v-model="form.exercise_type" filterable placeholder="请选择类型">
              <el-option label="单选题" value="单选题" />
              <el-option label="多选题" value="多选题" />
              <el-option label="判断题" value="判断题" />
              <el-option label="填空题" value="填空题" />
              <el-option label="写作题" value="写作题" />
              <el-option label="计算题" value="计算题" />
            </el-select>
          </el-form-item>
          <el-form-item label="题目内容" prop="content">
            <el-input v-model="form.content" type="textarea" :rows="3" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="答案" style="margin-bottom: 10px">
            <el-form-item
              v-for="(domain, index) in form.answer"
              v-show="form.answer.length > 0"
              :key="index"
              label-width="0px"
              :label="mapAnswer(index)"
              :prop="mapAnswer(index)"
            >
              <el-row :gutter="10">
                <el-col :span="8" style="margin-top: 4px">
                  <el-input v-model="domain[mapAnswer(index)]" />
                </el-col>
                <el-col :span="6">
                  <el-button
                    style="font-size: 20px"
                    type="text"
                    icon="el-icon-delete"
                    @click.prevent="removeDomain(index)"
                  />
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-row>
                <el-col :span="10">
                  <el-button
                    style="width: 100%;margin-top: 10px;margin-bottom: 15px"
                    @click="addAnswer"
                  >添加答案</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form-item>
          <el-form-item label="题目解析" prop="analysis">
            <el-input v-model="form.analysis" type="textarea" :rows="3" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>-->
    </template>
  </BasicLayout>
</template>
<script>
import {
  getExercises,
  getConfigKey,
  // editExercises,
  delExercises
} from '@/api/admin/sys-course'
import { chooseExercises } from '@/api/admin/sys-question'
import Exercises from '@/components/Exercises'
export default {
  components: {
    Exercises
  },
  data() {
    return {
      topicType: {},
      courseId: null,
      subjectList: [],
      visible: false,
      routerData: {},
      form: {
        answer: []
      },
      rules: {},
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 5
      },
      // 总条数
      total: 0,
      subjectType: '',
      idList: [],
      urlTest: /^http(s|):\/\/\S*?\//
    }
  },
  created() {
    getConfigKey().then(response => {
      this.topicType = JSON.parse(response?.data?.configValue)
    })
    if (this.$route.params) {
      this.routerData = this.$route.params
      this.link_id = this.$route.params && Number(this.$route.params.id)
      this.chapter_id =
        this.$route.params && Number(this.$route.params.chapter_id)
      this.link_type =
        this.$route.params && Number(this.$route.params.link_type)
      this.getList()
      switch (this.link_type) {
        case 3:
          return (this.subjectType = 'editExercise')
        case 2:
          return (this.subjectType = 'editPractice')
        case 1:
          return (this.subjectType = 'EditNetworkCourse')
        default:
          break
      }
    }
  },
  methods: {
    getList() {
      getExercises({
        link_id: this.link_id,
        chapter_id: this.chapter_id,
        link_type: this.link_type
        // ...this.queryParams
      }).then(res => {
        const subjectData = res.data || []
        this.idList = subjectData.map(item => item.id)
        // this.total = res.data.count
        this.subjectList = subjectData?.map(item => {
          return {
            ...item,
            answer: item?.answer ? JSON.parse(item?.answer) : []
          }
        })
      })
    },
    addSubject() {
      this.visible = true
    },
    onClosed() {
      this.form = {}
      this.resetForm('form')
    },
    submitForm(ids) {
      const parmars = {
        link_id: this.link_id,
        chapter_id: this.chapter_id,
        link_type: this.link_type,
        question_bank_str: ids
      }
      chooseExercises(parmars).then(res => {
        this.visible = false
        this.getList()
      })
    },
    cancel() {
      this.visible = false
    },
    addAnswer() {
      this.form.answer.push({})
    },
    removeDomain(key) {
      const temp = this.form.answer
        .filter((value, index) => index !== key)
        .map((item, index) => {
          let s = ''
          Object.values(item).forEach(element => {
            s = element
          })
          return {
            [this.mapAnswer(index)]: s
          }
        })
      this.form.answer = temp
    },
    mapAnswer(answer) {
      const answerArr = answer.toString().split(',')
      const newArr = answerArr.map(item =>
        String.fromCharCode(65 + parseInt(item))
      )
      return newArr.join(',')
    },
    editSubject(value, key) {
      this.visible = true
      this.form = JSON.parse(JSON.stringify(value))
    },
    deleteSubject(value, key) {
      this.$confirm('是否确认删除', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delExercises({
            ids: [value.id],
            chapter_id: this.routerData.chapter_id,
            type: this.routerData.type_id
          }).then(res => {
            if (res.code === 200) {
              this.msgSuccess(res.msg)
              this.getList()
            } else {
              this.msgError(res.msg)
            }
          })
        })
        .catch(function() {})
    }
  }
}
</script>
<style>
.avatar{
  width: unset;
}
</style>
